/*
 * Copyright (C) 2014 Francisco José Morero Peyrona. All Rights Reserved.
 *
 * This file is part of JStatViewer project: https://code.google.com/p/jstat-viewer/
 *
 * GNU Classpath is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the free
 * Software Foundation; either version 3, or (at your option) any later version.
 *
 * Tapas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * Tapas; see the file COPYING.  If not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package jstatviewer.ui;

import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import jstatviewer.Main;

/**
 * A JPanel containing a toolbar and an area below to contain a GraphPanel.
 *
 * @author peyrona
 */
public final class MainPanel extends javax.swing.JPanel
{
    private File lastFolder;

    //----------------------------------------------------------------------------//

    /**
     * Creates new form MainPanel
     */
    public MainPanel()
    {
        initComponents();
        spnTimeInterval.setValue( 250 );
    }

    //----------------------------------------------------------------------------//

    private void newGraph()
    {
        List<File> lstLogs = openJStatsFiles();

        if( lstLogs != null )
        {
            for( File fLog : lstLogs )
            {
                String      tabCaption = fLog.getName();
                int         nInterval  = (Integer) spnTimeInterval.getValue();
                GraphPanel  graphPanel = new GraphPanel();

                tabbedPane.add( tabCaption, graphPanel );
                tabbedPane.setSelectedIndex( tabbedPane.getTabCount() - 1 );
                graphPanel.show( fLog, nInterval );
            }
        }
    }

    private void closeGraph()
    {
        if( tabbedPane.getSelectedIndex() > -1 )
        {
            tabbedPane.remove( tabbedPane.getSelectedIndex() );

            if( tabbedPane.getSelectedIndex() > -1 )
            {
                tabbedPane.setSelectedIndex( tabbedPane.getTabCount() - 1 );
            }
        }
    }

    private void showLeyends()
    {
        Leyends.show();
    }

    private List<File> openJStatsFiles()
    {
        List<File>              lstLogs = null;
        FileNameExtensionFilter filter  = new FileNameExtensionFilter( "JStats Log files", "log" );
        JFileChooser            chooser = new JFileChooser( lastFolder );
                                chooser.setFileFilter( filter );
                                chooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
                                chooser.setMultiSelectionEnabled( true );

        if( chooser.showOpenDialog( Main.getFrame() ) == JFileChooser.APPROVE_OPTION )
        {
            lastFolder = chooser.getSelectedFile().getParentFile();
            lstLogs    = Arrays.asList( chooser.getSelectedFiles() );

            // Quitamos los files que no se pueden leer
            Iterator<File> itr = lstLogs.iterator();

            while( itr.hasNext() )
            {
                if( ! itr.next().canRead() )
                {
                    itr.remove();
                    JOptionPane.showMessageDialog( Main.getFrame(), "File can not be read" );
                }
            }
        }

        return lstLogs;
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of
     * this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        toolBar = new javax.swing.JToolBar();
        btnNewGraph = new javax.swing.JButton();
        btnCloseGraph = new javax.swing.JButton();
        btnInfo = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jLabel1 = new javax.swing.JLabel();
        spnTimeInterval = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        tabbedPane = new javax.swing.JTabbedPane();

        toolBar.setRollover(true);
        toolBar.setName("toolBar"); // NOI18N

        btnNewGraph.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jstatviewer/ui/new.png"))); // NOI18N
        btnNewGraph.setText("New");
        btnNewGraph.setToolTipText("Open one or more log files");
        btnNewGraph.setFocusable(false);
        btnNewGraph.setName("btnNewGraph"); // NOI18N
        btnNewGraph.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnNewGraphActionPerformed(evt);
            }
        });
        toolBar.add(btnNewGraph);

        btnCloseGraph.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jstatviewer/ui/close.png"))); // NOI18N
        btnCloseGraph.setText("Close");
        btnCloseGraph.setToolTipText("Close highlighted tab");
        btnCloseGraph.setFocusable(false);
        btnCloseGraph.setName("btnCloseGraph"); // NOI18N
        btnCloseGraph.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnCloseGraphActionPerformed(evt);
            }
        });
        toolBar.add(btnCloseGraph);

        btnInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jstatviewer/ui/info.png"))); // NOI18N
        btnInfo.setText("Leyends");
        btnInfo.setToolTipText("Leyends");
        btnInfo.setFocusable(false);
        btnInfo.setName("btnInfo"); // NOI18N
        btnInfo.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnInfoActionPerformed(evt);
            }
        });
        toolBar.add(btnInfo);

        jSeparator1.setName("jSeparator1"); // NOI18N
        toolBar.add(jSeparator1);

        jLabel1.setText("Interval ");
        jLabel1.setToolTipText("Time interval between two consecutives values");
        jLabel1.setName("jLabel1"); // NOI18N
        toolBar.add(jLabel1);

        spnTimeInterval.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
        spnTimeInterval.setToolTipText("Time interval between two consecutives values");
        spnTimeInterval.setMaximumSize(new java.awt.Dimension(69, 28));
        spnTimeInterval.setMinimumSize(new java.awt.Dimension(69, 28));
        spnTimeInterval.setName("spnTimeInterval"); // NOI18N
        spnTimeInterval.setPreferredSize(new java.awt.Dimension(70, 28));
        toolBar.add(spnTimeInterval);

        jLabel2.setText("  ");
        jLabel2.setName("jLabel2"); // NOI18N
        toolBar.add(jLabel2);

        tabbedPane.setName("tabbedPane"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(tabbedPane)
                    .addComponent(toolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 674, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnNewGraphActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnNewGraphActionPerformed
    {//GEN-HEADEREND:event_btnNewGraphActionPerformed
        newGraph();
    }//GEN-LAST:event_btnNewGraphActionPerformed

    private void btnCloseGraphActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnCloseGraphActionPerformed
    {//GEN-HEADEREND:event_btnCloseGraphActionPerformed
        closeGraph();
    }//GEN-LAST:event_btnCloseGraphActionPerformed

    private void btnInfoActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnInfoActionPerformed
    {//GEN-HEADEREND:event_btnInfoActionPerformed
        showLeyends();
    }//GEN-LAST:event_btnInfoActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCloseGraph;
    private javax.swing.JButton btnInfo;
    private javax.swing.JButton btnNewGraph;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JSpinner spnTimeInterval;
    private javax.swing.JTabbedPane tabbedPane;
    private javax.swing.JToolBar toolBar;
    // End of variables declaration//GEN-END:variables
}